<?php

class LoginController extends Controller
{
	
	/**
	 * 
	 * @see Controller::defaultAction()
	 */
	public function defaultAction() {
		$loginView = new HTMLView( 'Login.tpl', $this->getSmarty() );
		$this->views->push( $loginView );
		
		$form = new Form();
		
		$username = new InputText( 'username', 'Gebruikersnaam', isset( $_POST['username'] ) ? $_POST['username'] : '' );
		$username->getValidator()->required('Dit veld moet ingevuld worden');
		$form->addChild($username);
		
		$password = new InputPassword( 'password', 'Wachtwoord', isset( $_POST['password'] ) ? $_POST['password'] : '' );
		$password->getValidator()->required('Dit veld moet ingevuld worden');
		$password->getValidator()->method( array( $this, 'validateUserData' ), 'Gebruikersnaam en/of wachtwoord is incorrect' );
		$form->addChild( $password );
		
		if( $_SERVER['REQUEST_METHOD'] == 'POST' && $form->isValid() )
		{
			header('Location: ./');
		}
		
		$form->addChild( new SubmitButton( 'submit', 'Inloggen' ) );
		
		$loginView->assign( 'form', $form );
	}
	
	public function validateUserData( FormElement $fe )
	{
		return User::login( $fe->getParent()->offsetGet('username')->getProperty('value'), $fe->getProperty('value') );
	}
}
